{% extends "base.html" %}
{% load static %}

{% block title %}数据分析仪表板{% endblock %}

{% block extra_css %}
<link href="{% static 'css/analytics.css' %}" rel="stylesheet">
<style>
.analytics-card {
    border: none;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    transition: transform 0.2s, box-shadow 0.2s;
}

.analytics-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0,0,0,0.15);
}

.stat-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 20px;
}

.stat-value {
    font-size: 2.5rem;
    font-weight: bold;
    margin-bottom: 5px;
}

.stat-label {
    font-size: 0.9rem;
    opacity: 0.9;
}

.kpi-card {
    border-left: 4px solid #007bff;
    padding: 15px;
    background: white;
    border-radius: 8px;
    margin-bottom: 15px;
}

.kpi-value {
    font-size: 1.8rem;
    font-weight: bold;
    margin-bottom: 5px;
}

.kpi-trend {
    font-size: 0.8rem;
}

.trend-up { color: #28a745; }
.trend-down { color: #dc3545; }
.trend-stable { color: #6c757d; }

.dashboard-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.quick-action-btn {
    border-radius: 8px;
    padding: 12px 20px;
    margin: 5px;
    border: none;
    font-weight: 500;
    transition: all 0.2s;
}

.quick-action-btn:hover {
    transform: translateY(-1px);
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2><i class="fas fa-chart-line text-primary"></i> 数据分析仪表板</h2>
            <p class="text-muted mb-0">实时数据洞察与智能分析</p>
        </div>
        <div>
            <button class="btn btn-outline-primary" onclick="refreshDashboard()">
                <i class="fas fa-sync-alt"></i> 刷新数据
            </button>
            <a href="{% url 'assets:report_designer' %}" class="btn btn-primary">
                <i class="fas fa-plus"></i> 创建报表
            </a>
        </div>
    </div>

    <!-- 快速统计 -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-value">{{ quick_stats.total_assets }}</div>
                <div class="stat-label">
                    <i class="fas fa-boxes"></i> 总资产数量
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                <div class="stat-value">{{ quick_stats.active_assets }}</div>
                <div class="stat-label">
                    <i class="fas fa-check-circle"></i> 在用资产
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                <div class="stat-value">{{ quick_stats.maintenance_this_month }}</div>
                <div class="stat-label">
                    <i class="fas fa-wrench"></i> 本月维修
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
                <div class="stat-value">{{ quick_stats.reports_count }}</div>
                <div class="stat-label">
                    <i class="fas fa-chart-bar"></i> 我的报表
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- 左侧内容 -->
        <div class="col-lg-8">
            <!-- KPI指标 -->
            <div class="card analytics-card mb-4">
                <div class="card-header bg-white">
                    <h5 class="mb-0">
                        <i class="fas fa-bullseye text-warning"></i> 关键指标 (KPI)
                    </h5>
                </div>
                <div class="card-body">
                    {% if kpi_metrics %}
                    <div class="row">
                        {% for kpi in kpi_metrics %}
                        <div class="col-md-6 col-lg-4">
                            <div class="kpi-card">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <div class="kpi-value">
                                            {% if kpi.current_value %}
                                                {{ kpi.current_value|floatformat:1 }}
                                            {% else %}
                                                --
                                            {% endif %}
                                        </div>
                                        <div class="text-muted">{{ kpi.name }}</div>
                                    </div>
                                    <div class="text-end">
                                        {% if kpi.trend == 'up' %}
                                        <i class="fas fa-arrow-up trend-up"></i>
                                        {% elif kpi.trend == 'down' %}
                                        <i class="fas fa-arrow-down trend-down"></i>
                                        {% else %}
                                        <i class="fas fa-minus trend-stable"></i>
                                        {% endif %}
                                    </div>
                                </div>
                                {% if kpi.target_value %}
                                <div class="progress mt-2" style="height: 4px;">
                                    <div class="progress-bar" role="progressbar" 
                                         style="width: {{ kpi.current_value|default:0|floatformat:0|add:0|mul:100|div:kpi.target_value|floatformat:0 }}%">
                                    </div>
                                </div>
                                {% endif %}
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    {% else %}
                    <div class="text-center py-4">
                        <i class="fas fa-bullseye fa-3x text-muted mb-3"></i>
                        <h6 class="text-muted">暂无KPI指标</h6>
                        <a href="{% url 'assets:kpi_metrics' %}" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-plus"></i> 创建KPI指标
                        </a>
                    </div>
                    {% endif %}
                </div>
            </div>

            <!-- 我的仪表板 -->
            <div class="card analytics-card mb-4">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="fas fa-tachometer-alt text-info"></i> 我的仪表板
                    </h5>
                    <a href="{% url 'assets:dashboard_list' %}" class="btn btn-sm btn-outline-primary">
                        查看全部
                    </a>
                </div>
                <div class="card-body">
                    {% if user_dashboards %}
                    <div class="dashboard-grid">
                        {% for dashboard in user_dashboards %}
                        <div class="card border">
                            <div class="card-body">
                                <h6 class="card-title">{{ dashboard.name }}</h6>
                                <p class="card-text text-muted small">{{ dashboard.description|truncatechars:60 }}</p>
                                <div class="d-flex justify-content-between align-items-center">
                                    <small class="text-muted">
                                        {{ dashboard.updated_at|date:"m-d H:i" }}
                                    </small>
                                    <a href="{% url 'assets:dashboard_view' dashboard.id %}" class="btn btn-sm btn-primary">
                                        查看
                                    </a>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    {% else %}
                    <div class="text-center py-4">
                        <i class="fas fa-tachometer-alt fa-3x text-muted mb-3"></i>
                        <h6 class="text-muted">暂无仪表板</h6>
                        <a href="{% url 'assets:dashboard_designer' %}" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-plus"></i> 创建仪表板
                        </a>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>

        <!-- 右侧内容 -->
        <div class="col-lg-4">
            <!-- 快速操作 -->
            <div class="card analytics-card mb-4">
                <div class="card-header bg-white">
                    <h5 class="mb-0">
                        <i class="fas fa-bolt text-warning"></i> 快速操作
                    </h5>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <a href="{% url 'assets:report_designer' %}" class="btn btn-outline-primary quick-action-btn">
                            <i class="fas fa-chart-line"></i> 创建报表
                        </a>
                        <a href="{% url 'assets:dashboard_designer' %}" class="btn btn-outline-info quick-action-btn">
                            <i class="fas fa-tachometer-alt"></i> 创建仪表板
                        </a>
                        <a href="{% url 'assets:kpi_metrics' %}" class="btn btn-outline-warning quick-action-btn">
                            <i class="fas fa-bullseye"></i> 管理KPI
                        </a>
                        <a href="{% url 'assets:data_analysis_tasks' %}" class="btn btn-outline-success quick-action-btn">
                            <i class="fas fa-brain"></i> 数据分析
                        </a>
                    </div>
                </div>
            </div>

            <!-- 最近报表 -->
            <div class="card analytics-card mb-4">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="fas fa-chart-bar text-success"></i> 最近报表
                    </h5>
                    <a href="{% url 'assets:report_list' %}" class="btn btn-sm btn-outline-primary">
                        查看全部
                    </a>
                </div>
                <div class="card-body">
                    {% if recent_reports %}
                    <div class="list-group list-group-flush">
                        {% for report in recent_reports %}
                        <div class="list-group-item border-0 px-0">
                            <div class="d-flex justify-content-between align-items-start">
                                <div class="flex-grow-1">
                                    <h6 class="mb-1">{{ report.name }}</h6>
                                    <p class="mb-1 text-muted small">{{ report.description|truncatechars:50 }}</p>
                                    <small class="text-muted">{{ report.updated_at|date:"m-d H:i" }}</small>
                                </div>
                                <div class="ms-2">
                                    <span class="badge bg-secondary">{{ report.get_report_type_display }}</span>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    {% else %}
                    <div class="text-center py-3">
                        <i class="fas fa-chart-bar fa-2x text-muted mb-2"></i>
                        <p class="text-muted mb-0">暂无报表</p>
                    </div>
                    {% endif %}
                </div>
            </div>

            <!-- 最近分析任务 -->
            <div class="card analytics-card">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="fas fa-brain text-purple"></i> 分析任务
                    </h5>
                    <a href="{% url 'assets:data_analysis_tasks' %}" class="btn btn-sm btn-outline-primary">
                        查看全部
                    </a>
                </div>
                <div class="card-body">
                    {% if recent_tasks %}
                    <div class="list-group list-group-flush">
                        {% for task in recent_tasks %}
                        <div class="list-group-item border-0 px-0">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1">{{ task.name }}</h6>
                                    <small class="text-muted">{{ task.get_task_type_display }}</small>
                                </div>
                                <div>
                                    {% if task.status == 'completed' %}
                                    <span class="badge bg-success">已完成</span>
                                    {% elif task.status == 'running' %}
                                    <span class="badge bg-primary">分析中</span>
                                    {% elif task.status == 'failed' %}
                                    <span class="badge bg-danger">失败</span>
                                    {% else %}
                                    <span class="badge bg-secondary">等待中</span>
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    {% else %}
                    <div class="text-center py-3">
                        <i class="fas fa-brain fa-2x text-muted mb-2"></i>
                        <p class="text-muted mb-0">暂无分析任务</p>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 刷新仪表板
function refreshDashboard() {
    // 显示加载状态
    const refreshBtn = document.querySelector('[onclick="refreshDashboard()"]');
    const originalText = refreshBtn.innerHTML;
    refreshBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 刷新中...';
    refreshBtn.disabled = true;
    
    // 更新KPI指标
    fetch('/assets/analytics/api/update-kpi/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken'),
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('success', `成功更新 ${data.updated_count} 个KPI指标`);
            // 刷新页面
            setTimeout(() => {
                location.reload();
            }, 1000);
        } else {
            showAlert('danger', data.message || '刷新失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('danger', '刷新失败');
    })
    .finally(() => {
        refreshBtn.innerHTML = originalText;
        refreshBtn.disabled = false;
    });
}

// 工具函数
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function showAlert(type, message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    const container = document.querySelector('.container-fluid');
    container.insertBefore(alertDiv, container.firstChild);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 可以添加一些初始化逻辑
    console.log('Analytics dashboard loaded');
});
</script>
{% endblock %}